frappe.ui.form.on('Stock Entry', {
    setup: function (frm) {
		frm.set_query('custom_reason', function (doc) {			
			return {
				filters: {
					'company': doc.company,
					'stock_entry_type': doc.stock_entry_type,
				}
			}
		});
        // 取物料主数据设置的单位
                
        frm.set_query("uom", "items", function (doc, cdt, cdn) {
            let row = locals[cdt][cdn];
            return {
                query:
                    "erpnext.accounts.doctype.pricing_rule.pricing_rule.get_item_uoms",
                filters: {
                    value: row.item_code,
                    apply_on: "Item Code",
                            },
                };
            });


	},
    custom_reason(frm){
        if (frm.doc.custom_reason){
            let filters = {'reason': frm.doc.custom_reason,
                'company': frm.doc.company    
            }            
            frappe.call({
                method: "frappe.client.get_value",
    			args: {
    				doctype: "Stock Entry Reason",
    				filters: filters,
    				fieldname:"account",
    				// parent:"Material Issue Reason Code"
    			},
            })
            .then(r=>{
                if (!r.exc){
                    // console.log("执行了")
                    frm.set_value('custom_opposite_account', r.message.account);
                }
            })
        }
        else {
            frm.set_value('custom_opposite_account', "")
        }  
    },
    stock_entry_type(frm){
        frm.set_value('custom_opposite_account', "")
        frm.set_value('custom_reason', "")
    },

    refresh(frm) {
		// 显示当前物料在来源仓库中的数量
		frm.set_query('s_warehouse', 'items', function(doc, cdt, cdn) {
        		var row  = locals[cdt][cdn];
        		var filters = erpnext.queries.warehouse(frm.doc);
        		if(row.item_code){
        			$.extend(filters, {"query":"erpnext.controllers.queries.warehouse_query"});
        			filters["filters"].push(["Bin", "item_code", "=", row.item_code]);
        		}
        		return filters
        	});
	}
})